
package com.e885.util.web;

import javax.servlet.http.HttpServletRequest;

import com.e885.util.UUIDHexGenerator;

/**
 * Token
 * 
 * @author Eric.Kao(gau168.gau@msa.hinet.net)
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2001-2008
 */

public class CommandToken
{
	public static String TOKEN = "token";

	/**
	 * 取得 token value 從 request.getAttribute(), 其 key 是 <code>TOKEN</code>
	 * 
	 * @param request
	 * @return
	 */
	public static String get( HttpServletRequest request )
	{
		return get( request, TOKEN );
	}

	/**
	 * 取得 token value 從 request.getAttribute()
	 * 
	 * @param request
	 * @param key
	 * @return
	 */
	public static String get( HttpServletRequest request, String key )
	{
		return ( String )request.getAttribute( key );
	}

	/**
	 * 驗證 token
	 * 
	 * @param request a reqeust
	 * @return if ture, token is valid.
	 */
	public static boolean isValid( HttpServletRequest request )
	{
		return isValid( request, TOKEN );
	}

	/**
	 * 驗證 token
	 * 
	 * @param request a requst
	 * @param key a key
	 * @return if true, token is valid
	 */
	public static boolean isValid( HttpServletRequest request, String key )
	{
		String requestToken = request.getParameter( key );
		String sessionToken = ( String )request.getSession( true ).getAttribute( key );

		if( requestToken == null || sessionToken == null )
			return false;

		return requestToken.equals( sessionToken );
	}

	/**
	 * 設定 token, token 來源是 32 碼的 uuid
	 * 
	 * @param request a request
	 */
	public static void set( HttpServletRequest request )
	{
		set( request, TOKEN );
	}

	/**
	 * 設定 token, token 來源是 32 碼的 uuid
	 * 
	 * @param request a request
	 * @param key a key
	 */
	public static void set( HttpServletRequest request, String key )
	{
		String token = new UUIDHexGenerator().generate();

		request.setAttribute( key, token );
		request.getSession( true ).setAttribute( key, token );
	}
}
